<template>
  <div class="container">
    <Breadcrumb :items="['menu.survey', 'menu.survey.createSurvey']" />
    <a-spin :loading="loading" style="width: 100%">
      <!--<a-card>-->
      <div>
        <div class="left" style="float: left">
          <a-table
            row-key="id"
            :loading="loading"
            :pagination="pagination"
            :data="renderData"
            :bordered="false"
            @page-change="onPageChange"
          >
            <template #columns>
              <a-table-column title="题干" data-index="stem" />
              <a-table-column title="类型" data-index="questionType">
              </a-table-column>
              <a-table-column
                :title="$t('searchTable.columns.operations')"
                data-index="operations"
              >
                <template #cell="record">
                  <a-button type="text" size="small" @click="modifyQ(record)">
                    添加
                  </a-button>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
        <div class="right" style="float: right">
          <!--让他居中  已经居中了，让题目变的宽一点-->
          <a-form
            :model="modelForm"
            :rule="rules"
            style="display: flex; align-items: center; justify-content: center"
            @submit="handleSubmit"
          >
            <!-- <vuedraggable v-model="modelForm.questions" item-key="index" class="wrapper" @end="end"> -->
            <a-form-item field="name" label="问卷名称" style="width: 70%">
              <a-input v-model="modelForm.name" placeholder="请输入问卷名称 " />
            </a-form-item>
            <a-form-item
              field="answerLimit"
              label="答卷次数"
              style="width: 70%"
            >
              <a-input
                v-model="modelForm.answerLimit"
                placeholder="请输入答卷次数"
              />
            </a-form-item>
            <a-form-item
              field="description"
              label="问卷描述"
              style="width: 70%"
            >
              <a-textarea
                v-model="modelForm.description"
                placeholder="请输入问卷描述"
              />
            </a-form-item>
            <a-form-item
              field="rangeValue"
              label="答卷时间范围"
              style="width: 70%"
            >
              <a-range-picker
                v-model="rangeValue"
                style="width: 360px; margin: 0 24px 24px 0"
              />
            </a-form-item>
            <a-form-item field="updater" label="面向群组ID" style="width: 70%">
              <a-input v-model="modelForm.updater" placeholder="无" />
            </a-form-item>
            <!-- 循环读取问题
                首先要实现的是nextId的获取
                style="width: 70%"
               -->
            <div v-for="(item, index) in modelForm.questions" :key="index">
              <a-collapse default-active-key="1">
                <a-collapse-item key="1" header="题目">
                  <template #item="index">
                    第{{ index + 1 }}题,题目:{{ item.stem }}
                  </template>
                  <a-form-item
                    :field="`questions.${index}.questionType`"
                    :label="`问题${index + 1}类型`"
                    :rules="{
                      required: true,
                      message: '请选择问题类型',
                      trigger: 'change',
                    }"
                  >
                    <!--选择题目类型-->
                    <a-radio-group v-model="item.questionType">
                      <a-radio :value="0">单选</a-radio>
                      <a-radio :value="1">多选</a-radio>
                      <a-radio :value="2">填空</a-radio>
                    </a-radio-group>
                  </a-form-item>
                  <a-form-item
                    :field="`questions.${index}.stem`"
                    :label="问题"
                    :rules="{
                      required: true,
                      message: '请填写问题',
                      trigger: 'change',
                    }"
                  >
                    <a-input
                      v-model.trim="item.stem"
                      :style="{ width: '258px' }"
                      placeholder="请填写问题"
                      allow-clear
                    />
                  </a-form-item>
                  <!-- 答案
                      这个就是单选或者多选
                        注意 单选题的时候才有题目跳转
                          1。在每个单选题选项的后面增加一个跳转的目的地
                          2。但这有个问题，就是我选择跳转后，需要能再新建一个题目
                          3。记录从哪个选项走的，从哪个题走的
                    -->
                  <template v-if="item.questionType != 2">
                    <a-form-item
                      v-for="(opt, idx) in item.choices"
                      :key="idx"
                      :label="`选项${idx + 1}`"
                      :field="`questions.${index}.choices.${idx}.content`"
                      :rules="[
                        {
                          required: true,
                          message: '请输入答案',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <a-input
                        v-model.trim="opt.content"
                        :style="{ width: '258px' }"
                        placeholder="请输入答案"
                        allow-clear
                      />
                      <!-- 加一个新的输入框，下一个题去哪里
                            当失去焦点或者回车，会新建一个题 但要判断一下有没有输入
                            我还得记录是哪个选项进行的跳转
                        -->
                      <a-input
                        v-model.trim="opt.goTo"
                        placeholder="可输入跳转题号"
                        style="
                          width: 150px;
                          margin-left: 10px;
                          border-color: black;
                        "
                        @change="goToNextQuestion(index, idx)"
                      >
                      </a-input>
                      <a-button
                        style="margin-left: 20px"
                        type="text"
                        @click.prevent="removeDomain(index, idx)"
                        >删除</a-button
                      >
                    </a-form-item>
                  </template>

                  <a-form-item>
                    <a-button
                      v-show="item.questionType != 2"
                      @click="addDomain(index)"
                      >新增选项</a-button
                    >
                    <a-button @click="removeQuestion(index)">删除题目</a-button>
                  </a-form-item>
                </a-collapse-item>
              </a-collapse>
            </div>
            <!-- </vuedraggable> -->
            <a-form-item>
              <a-button @click="addQuestion">新增题目</a-button>
              <a-button style="margin-left: 10px" @click="addSubmit()"
                >提交</a-button
              >
            </a-form-item>
          </a-form>
        </div>
      </div>

      <!--</a-card>-->
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
  import useLoading from '@/hooks/loading';
  import {
    submitChannelForm,
    BaseInfoModel,
    ChannelInfoModel,
    UnitChannelModel,
  } from '@/api/form';
  import {
    createSurvey,
    deleteQuestion,
    getQuestionDetail,
    PolicyParams,
    questionList,
  } from '@/api/list';
  import vuedraggable from 'vuedraggable';
  import { ref, reactive } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import { Pagination } from '@/types/global';
  import { useSurveyStore } from '@/store';
  import BaseInfo from './components/base-info.vue';
  import ChannelInfo from './components/channel-info.vue';
  import Success from './components/success.vue';
  import ChooseQuestionType from './components/choose-question-type.vue';
  import ChoiceQuestion from './components/choice-question.vue';
  import uuid from './uuid';

  // components:{ vuedraggable }
  const { setLoading } = useLoading(true);
  const userId = 'a9e96ba9-e95a-4989-a015-17ab9f5d3047';
  // 这是整个form 的数据，用在了最大的表格form上，注意question的循环
  const modelForm = reactive({
    name: '',
    description: '',
    managedBy: 'admin',
    rangeValue: [Date.now(), Date.now()],
    // 这个不应该在外面吗，上限
    answerLimit: '',
    updater: '',
    questions: [
      {
        id: uuid.uuid(),
        questionType: '1',
        stem: '',
        // 下一个题的Id
        nextId: '',
        choices: [
          {
            id: uuid.uuid(),
            content: '',
            // 这个选项的下一个题
            goTo: '',
          },
        ],
      },
    ],
  });
  // const end(e) = {
  //   $refs.modelForm.clearValidate()
  // }
  const init = () => {
    if (useSurveyStore().groupId !== '') {
      modelForm.updater = useSurveyStore().groupId;
    }
  };
  init();
  const removeDomain = (index: number, idx: number) => {
    modelForm.questions[index].choices.splice(idx, 1);
  };
  const addDomain = (index: number) => {
    modelForm.questions[index].choices.push({ id: uuid.uuid(), content: '' });
  };
  const addSubmit = async () => {
    setLoading(true);
    console.log(modelForm);

    try {
      let final = {
        name: '',
        description: '',
        managedBy: 'admin',
        rangeValue: [Date.now(), Date.now()],
        // 这个不应该在外面吗，上限
        answerLimit: '',
        questions: [],
        startTime: 0,
        endTime: 0,
      };
      final = modelForm;
      const startTime = modelForm.rangeValue[0];
      const endTime = modelForm.rangeValue[1];
      final.startTime = startTime;
      final.endTime = endTime;
      console.log(`final ${final}`);
      await createSurvey(userId, final);
      Message.success('success');
    } catch (err) {
      // throw err
    } finally {
      setLoading(false);
    }
  };

  // 删除题目
  const removeQuestion = (index) => {
    modelForm.questions.splice(index, 1);
    // 先不考虑这里了
    // allQuestionNumber -= 1;
  };

  // 新增题目
  const addQuestion = () => {
    modelForm.questions.push({
      id: uuid.uuid(),
      questionType: '',
      stem: '',
      // 下一个题的Id
      nextId: '',
      choices: [{ id: uuid.uuid(), content: '' }],
    });
    // 然后要告诉上一个题的nextId
    modelForm.questions[allQuestionNumber].nextId =
      modelForm.questions[allQuestionNumber + 1].id;
    // 这里是加一个题
    allQuestionNumber += 1;

    // 看一下咋样
    console.log(modelForm);
  };

  // 这里写跳转的逻辑
  //  首先是nextId的问题，需要根据下一个题传给上一个题
  //  我给一个初始的题目数量，然后对他进行操作
  //  新增一个题目就+1 删除一个就-1
  let allQuestionNumber = 0;

  // 上面的变量实现了下一个题，然后就是实现每个问题选项的nextId了
  // 这个变量是记录是哪个选项的 就是A还是B进行的跳转
  let fromOpt = 0;
  // 还得记录从哪个题跳转的
  let fromQuestion = 0;

  // 下面是通过可跳转题号新建题
  // 第一个是哪一个题，第二个是哪一个选项
  const goToNextQuestion = (index: number, idx: number) => {
    // 先获取一下这个跳转
    fromQuestion = index;
    fromOpt = idx;

    // 先判断一下有没有东西 没有东西不用新建
    if (modelForm.questions[fromQuestion].choices[fromOpt].goTo === '') {
      return;
    }

    // 还是新建一个题
    modelForm.questions.push({
      id: uuid.uuid(),
      questionType: '',
      stem: '',
      // 下一个题的Id
      nextId: '',
      choices: [{ id: uuid.uuid(), content: '' }],
    });
    // 题数肯定得 +1
    allQuestionNumber += 1;
    // 这里要回填 告诉跳转过来的题，下一个题的id是啥
    // 赋值下一个题的id
    modelForm.questions[fromQuestion].choices[fromOpt].goTo =
      modelForm.questions[allQuestionNumber].id;

    // 看一下咋样
    console.log(modelForm);
  };

  // 左侧问题列表
  const generateFormModel = () => {
    return {
      number: '',
      name: '',
      contentType: '',
      filterType: '',
      createdTime: [],
      status: '',
    };
  };
  const renderData = ref([]);
  const basePagination: Pagination = {
    page: 1,
    limit: 20,
  };
  const formModel = ref(generateFormModel());
  const pagination = reactive({
    ...basePagination,
  });
  const fetchData = async (params: PolicyParams = { page: 1, limit: 20 }) => {
    setLoading(true);
    try {
      const { data } = await questionList(params);
      renderData.value = data.list;
      pagination.page = params.page;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as PolicyParams);
  };
  const onPageChange = (page: number) => {
    fetchData({ ...basePagination, page });
  };
  const deleteQ = async (data) => {
    // console.log([data.record.id]);

    await deleteQuestion([data.record.id]);
    Message.success('删除成功');
  };
  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  // 接收一下
  const questionDetail = ref();
  // 点击添加之后，往问卷里面添加
  const modifyQ = async (data: any) => {
    console.log(data.record.id);
    const toBack = [data.record.id];
    // const toBack=ref({id:data.record.id});
    // console.log(toBack)
    // 发请求 获取整个问题
    try {
      questionDetail.value = await getQuestionDetail(toBack);
      console.log(questionDetail.value);
      // Message.success('success');
    } catch (err) {
      // throw err
    } finally {
      setLoading(false);
    }
    // 现在获取到了，要添加到右边的创建问卷中
    // 让我来想一想……
    console.log(questionDetail.value.data[0].stem);
    modelForm.questions[allQuestionNumber].id = questionDetail.value.data[0].id;
    modelForm.questions[allQuestionNumber].stem =
      questionDetail.value.data[0].stem;
    modelForm.questions[allQuestionNumber].questionType =
      questionDetail.value.data[0].questionType;
    modelForm.questions[allQuestionNumber].choices =
      questionDetail.value.data[0].choiceItems;

    // 还得告诉上一个题的nextid是啥
    modelForm.questions[allQuestionNumber - 1].nextId =
      questionDetail.value.data[0].id;
  };
</script>

<script lang="ts">
  export default {
    name: 'Step',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  .wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 64px 0;
    background-color: var(--color-bg-2);

    :deep(.arco-form) {
      .arco-form-item {
        &:last-child {
          margin-top: 20px;
        }
      }
    }
  }

  .steps {
    margin-bottom: 76px;
  }

  .left {
    float: left;
    width: 400px;
    height: 100%;
    //background-color: red;
  }

  .right {
    //margin-left: -100px;
    //margin-right: 100px;
    width: 700px;
    //background-color: blue;
  }
</style>
